<template>
  <el-container class="main-container">
    <el-aside :width="isCollapse ? '64px' : '240px'" class="sidebar-container">
      <div class="logo">
        <transition name="fade">
          <span v-if="!isCollapse" class="logo-text">会员管理系统</span>
          <span v-else class="logo-icon">SP</span>
        </transition>
      </div>
      
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :collapse-transition="false"
        class="sidebar-menu"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        @select="handleMenuSelect"
      >
        <el-menu-item
          v-for="route in menuRoutes"
          :key="route.path"
          :index="route.path"
        >
          <el-icon><component :is="route.meta?.icon" /></el-icon>
          <template #title>{{ route.meta?.title }}</template>
        </el-menu-item>
      </el-menu>
    </el-aside>
    
    <el-container>
      <el-header class="header-container">
        <div class="header-left">
          <el-icon
            class="collapse-icon"
            @click="toggleCollapse"
          >
            <Expand v-if="isCollapse" />
            <Fold v-else />
          </el-icon>
          
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-if="currentRoute.meta.title">
              {{ currentRoute.meta.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="header-right">
          <!-- 消息通知 -->
          <el-badge :value="notificationStore.unreadCount" :hidden="notificationStore.unreadCount === 0">
            <el-button
              circle
              :icon="Bell"
              @click="showNotificationDrawer = true"
            />
          </el-badge>
          
          <!-- 用户信息 -->
          <el-dropdown @command="handleCommand">
            <div class="user-info">
              <el-avatar :src="authStore.userInfo?.avatar" :size="32">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="username">{{ authStore.userInfo?.nickname || authStore.userInfo?.username || '用户' }}</span>
              <el-icon><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item command="changePassword">
                  <el-icon><Lock /></el-icon>
                  修改密码
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
    
    <!-- 消息通知抽屉 -->
    <NotificationDrawer v-model="showNotificationDrawer" />
    
    <!-- 修改密码对话框 -->
    <ChangePassword v-model="showChangePassword" />
  </el-container>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useNotificationStore } from '@/stores/notification'
import {
  Expand,
  Fold,
  Bell,
  User,
  ArrowDown,
  SwitchButton,
  Lock
} from '@element-plus/icons-vue'
import NotificationDrawer from '@/components/NotificationDrawer.vue'
import ChangePassword from '@/components/ChangePassword.vue'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const notificationStore = useNotificationStore()

const isCollapse = ref(false)
const showNotificationDrawer = ref(false)
const showChangePassword = ref(false)

const currentRoute = computed(() => route)

// 获取当前激活的菜单项路径
// 菜单项的 index 使用的是子路由的 path（相对路径，如 'dashboard'）
// 需要确保 activeMenu 返回的值与菜单项的 index 匹配
const activeMenu = computed(() => {
  // 获取当前路由名称
  const routeName = route.name as string
  
  // 如果是博客详情页，返回 blogs
  if (routeName === 'BlogDetail') {
    return 'blogs'
  }
  
  // 获取当前路由匹配的子路由
  const matched = route.matched
  // 找到最后一个匹配的子路由（最具体的那个）
  for (let i = matched.length - 1; i >= 0; i--) {
    const match = matched[i]
    // 如果是子路由且有 meta.title 且不是隐藏的，说明是菜单项
    if (match.meta?.title && !match.meta?.hidden && match.path !== '/') {
      // 返回子路由的 path（已经是相对路径，如 'dashboard'）
      // 但需要确保格式正确，去掉开头的 /
      let path = match.path
      if (path.startsWith('/')) {
        path = path.slice(1)
      }
      // 处理动态路由：blogs/:id -> blogs
      if (path.includes('/:')) {
        path = path.split('/:')[0]
      }
      return path
    }
  }
  
  // 如果没有找到匹配的子路由，从当前路径中提取
  // 例如：/dashboard -> dashboard
  const path = route.path
  if (path === '/') {
    return 'dashboard' // 默认激活仪表盘
  }
  
  // 处理博客详情页：/blogs/:id -> blogs
  if (path.startsWith('/blogs/') && path !== '/blogs') {
    return 'blogs'
  }
  
  // 处理其他路径
  let result = path.startsWith('/') ? path.slice(1) : path
  // 处理动态路由参数
  if (result.includes('/')) {
    result = result.split('/')[0]
  }
  return result
})

const menuRoutes = computed(() => {
  return route.matched[0]?.children?.filter((child: any) => child.meta?.title && !child.meta?.hidden) || []
})

const toggleCollapse = (): void => {
  isCollapse.value = !isCollapse.value
}

// 处理菜单选择
const handleMenuSelect = (index: string): void => {
  // 找到对应的路由
  const selectedRoute = menuRoutes.value.find((r: any) => r.path === index)
  if (selectedRoute && selectedRoute.name) {
    // 使用命名路由进行跳转，避免相对路径问题
    router.push({ name: selectedRoute.name })
  } else if (selectedRoute) {
    // 如果没有命名路由，使用路径跳转
    router.push(selectedRoute.path)
  }
}

const handleCommand = async (command: string): Promise<void> => {
  switch (command) {
    case 'profile':
      router.push({ name: 'Profile' })
      break
    case 'changePassword':
      showChangePassword.value = true
      break
    case 'logout':
      await authStore.logout()
      router.push({ name: 'Login' })
      break
  }
}

// 通知刷新定时器
let notificationRefreshInterval: ReturnType<typeof setInterval> | null = null

onMounted(async (): Promise<void> => {
  // 初始化时获取用户信息
  if (authStore.isAuthenticated && !authStore.userInfo) {
    await authStore.fetchCurrentUser()
  }
  
  // 如果已登录，加载未读通知数量
  if (authStore.isAuthenticated) {
    // 初始加载未读通知数量
    notificationStore.fetchUnreadCount().catch(() => {
      // 静默失败，不影响主流程
    })
    
    // 每60秒刷新一次未读通知数量
    notificationRefreshInterval = setInterval(() => {
      if (authStore.isAuthenticated) {
        notificationStore.fetchUnreadCount().catch(() => {
          // 静默失败
        })
      }
    }, 60000)
  }
})

onUnmounted((): void => {
  if (notificationRefreshInterval) {
    clearInterval(notificationRefreshInterval)
  }
})
</script>

<style lang="scss" scoped>
.main-container {
  height: 100vh;
}

.sidebar-container {
  background-color: #304156;
  transition: width 0.3s;
  overflow: hidden;
  
  .logo {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #2b3a4a;
    color: white;
    font-weight: 700;
    font-size: 18px;
    
    .logo-text {
      white-space: nowrap;
    }
    
    .logo-icon {
      font-size: 20px;
    }
  }
  
  .sidebar-menu {
    border: none;
    height: calc(100vh - 60px);
    overflow-y: auto;
    
    :deep(.el-menu-item) {
      height: 50px;
      line-height: 50px;
      
      &:hover {
        background-color: #263445 !important;
      }
      
      &.is-active {
        background-color: #1890ff !important;
        color: white !important;
      }
    }
  }
}

.header-container {
  background: white;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 20px;
    
    .collapse-icon {
      font-size: 20px;
      cursor: pointer;
      color: #666;
      transition: color 0.3s;
      
      &:hover {
        color: #409EFF;
      }
    }
  }
  
  .header-right {
    display: flex;
    align-items: center;
    gap: 20px;
    
    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      padding: 4px 12px;
      border-radius: 20px;
      transition: background-color 0.3s;
      
      &:hover {
        background-color: #f5f5f5;
      }
      
      .username {
        font-size: 14px;
        color: #333;
      }
    }
  }
}

.main-content {
  background-color: #f5f5f5;
  padding: 20px;
  overflow-y: auto;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>

